#!/bin/bash -e

pushd $(dirname "$0") > /dev/null
cd ..
cp Signing.xcconfig{.tpl,}
popd > /dev/null

no_available_code_signing_certificate() {
    echo 'No available code signing certificate. Use ad-hoc certificate.' >&2
    echo 'If you want to use your own certificate, create a signing certificate in Xcode (https://help.apple.com/xcode/mac/current/#/dev154b28f09) and re-run this command.' >&2
    exit 0
}

search_code_signing_certificate() {
    CN=$(security find-identity -vp codesigning | grep "$1" | head -1 | awk -F\" '{ print $2 }')
    if [[ -n "$CN" ]]; then
        echo "Found CN: $CN" >&2
        DEVELOPMENT_TEAM=$(certtool y | grep "$CN" -A2 | grep OrgUnit | head -1 | awk -F': ' '{ print $2 }')
        if [[ -z "$DEVELOPMENT_TEAM" ]]; then
            no_available_code_signing_certificate
        fi
        CODE_SIGN_IDENTITY="$1"
    fi
}

if [[ -z "$DEVELOPMENT_TEAM" ]]; then
    search_code_signing_certificate "Developer ID Application"
fi
if [[ -z "$DEVELOPMENT_TEAM" ]]; then
    search_code_signing_certificate "Apple Development"
fi
if [[ -z "$DEVELOPMENT_TEAM" ]]; then
    no_available_code_signing_certificate
fi

pushd $(dirname "$0") > /dev/null
cd ..
cp Signing.xcconfig{.tpl,}
sed -i '' "s/DEVELOPMENT_TEAM =/DEVELOPMENT_TEAM = $DEVELOPMENT_TEAM/" Signing.xcconfig
if [[ -n "$CODE_SIGN_IDENTITY" ]]; then
    echo "CODE_SIGN_IDENTITY = $CODE_SIGN_IDENTITY" >> Signing.xcconfig
fi
popd > /dev/null

echo "DEVELOPMENT_TEAM is configured to $DEVELOPMENT_TEAM." >&2
if [[ -n "$CODE_SIGN_IDENTITY" ]]; then
    echo "CODE_SIGN_IDENTITY is configured to $CODE_SIGN_IDENTITY" >&2
fi
